<?php

namespace Beerus\Modules\CategoryEntrance\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\ShopCategoryClassify as mShopCategoryClassify;
use Biz\model\CategoryStatusMap as mCategoryStatusMap;
use Biz\service\ShopClassify as sShopClassify;
use Doraemon\model\Category as mCategory;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use App\Exceptions\InputErrorException;

class ClassifyMapController extends Controller
{

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }


    /**
     * 前台一级类目列表
     * @param Content $content
     * @return Content
     */
    public function list(Content $content)
    {

        $firstClassfies = sShopClassify::admClassifiesOrCates();
        $gridModel = new pGridDataModel($firstClassfies['list']);
        $categoryGird = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->column('id')->sort();
            $grid->column('classify_name', '前台一级分类名');
            $grid->column('status', '隐藏')->switchToggle([
                'on' => [
                    'value' => mShopCategoryClassify::STATUS_NORMAL,
                    'text' => '展示'
                ],
                'off' => [
                    'value' => mShopCategoryClassify::STATUS_HIDE,
                    'text' => '隐藏'
                ]
            ]);
            $grid->column('classifies', '前台二级分类')->display(function () {
                $format = [];
                if ($this->classifies) {
                    foreach ($this->classifies as $classify) {
                        $format[] = "<a href='/admin/categoryEntrance/classifyMap/{$classify['parent_id']}/edit/{$classify['id']}/edit'>{$classify['classify_name']}</a>";
                    }
                }
                return $format;
            })->label('default');
        });
        return $content->header('前后台类目关联')->row($categoryGird);
    }

    /**
     * 前台一级类目编辑页
     * @param Content $content
     * @param int $firClassifyId
     * @return Content
     */
    public function classifyEdit(Content $content, $firClassifyId = 0)
    {
        $tab = new Tab();
        //基础信息
        $firClassifyInfo = [];
        if ($firClassifyId) {
            $firClassifyInfo = sShopClassify::admGetClassifyById($firClassifyId);
        }
        $basicForm = new Form($firClassifyInfo);
        $basicForm->text('classify_name', '一级分类名')->rules('required|min:1');
        $basicForm->action('/admin/categoryEntrance/classifyMap/' . $firClassifyId . '/save');
        $tab->add('基础信息', $basicForm);
        if ($firClassifyId) {
            $secGird = $this->childClassifyGrid($firClassifyId, mShopCategoryClassify::DEEP_SECOND_CLASSIFY, $firClassifyId);
            $tab->add('前台子类目', $secGird);
        }
        $content->header('前台一级类目配置' . ($firClassifyId ? "-" . $firClassifyInfo['classify_name'] : ""))
            ->breadcrumb([
                'text' => '前台类目列表',
                'url' => '/categoryEntrance/classifyMap'
            ], ['text' => '前台一级类目配置'])
            ->row($tab);
        return $content;
    }

    private static function getCategoryStatusMap($classifyId, &$childClassifyInfo)
    {
        $childClassifyInfo['decoration_status'] = [];
        $childClassifyInfo['house_status'] = [];

        $info = mCategoryStatusMap::getInfoByCategoryId($classifyId);

        if($info) {
            foreach ($info as $item) {
                if($item['status_type'] == mCategoryStatusMap::TYPE_STATUS_DECORATION) {
                    $childClassifyInfo['decoration_status'][] = $item['user_status'];
                } else {
                    $childClassifyInfo['house_status'][] = $item['user_status'];
                }
            }
        }

        return $childClassifyInfo;
    }

    /**
     * 前台二/三级类目编辑页
     * @param Content $content
     * @param $firClassifyId
     * @param int $secClassifyId
     * @param int $thirdClassifyId
     * @return Content
     */
    public function childClassifyEdit(Request $request, Content $content, $firClassifyId, $secClassifyId = 0, $thirdClassifyId = 0)
    {
        $deep = $request->route()->getName() ?: ($thirdClassifyId ? mShopCategoryClassify::DEEP_THIRD_CLAORCATE : mShopCategoryClassify::DEEP_SECOND_CLASSIFY);
        $classifyId = $deep == mShopCategoryClassify::DEEP_SECOND_CLASSIFY ? $secClassifyId : $thirdClassifyId;
        $tab = new Tab();
        $childClassifyInfo = ['cate_ids' => []];
        if ($classifyId) {
            $childClassifyInfo = sShopClassify::admGetClassifyById($classifyId);
        }
        $lastCategories = mCategory::getSelectLastStageCate(2);

        self::getCategoryStatusMap($classifyId, $childClassifyInfo); // 获取类目与 （房屋状态 && 装修状态） 的映射

        $basicForm = new Form($childClassifyInfo);
        $basicForm->hidden('id');
        $basicForm->hidden('deep')->default($deep);
        $basicForm->hidden('parent_id')->default($deep == mShopCategoryClassify::DEEP_SECOND_CLASSIFY ? $firClassifyId : $secClassifyId);
        $basicForm->text('classify_name', mShopCategoryClassify::DEEP_CLASSIFY_DISPALY[$deep] . '级分类名');
        $basicForm->imgUpload('icon', 'icon');
        $basicForm->multipleSelect('cate_ids', '关联后台类目')->options($lastCategories);
        $basicForm->checkbox('decoration_status', '推荐给-装修状态')->options(mCategoryStatusMap::DECORATION_STATUS_DESC)->canCheckAll();
        $basicForm->checkbox('house_status', '推荐给-房屋状态')->options(mCategoryStatusMap::HOUSE_STATUS)->canCheckAll();
        switch ($deep) {
            case mShopCategoryClassify::DEEP_SECOND_CLASSIFY:
                $basicForm->action('/admin/categoryEntrance/classifyMap/' . $firClassifyId . '/edit/' . $classifyId . '/save');
                $content->header('前台' . mShopCategoryClassify::DEEP_CLASSIFY_DISPALY[$deep] . '级类目配置' . ($classifyId ? "-" . $childClassifyInfo['classify_name'] : ""))
                    ->breadcrumb([
                        'text' => '前台类目列表',
                        'url' => '/categoryEntrance/classifyMap'
                    ], [
                        'text' => '前台一级类目列表',
                        'url' => '/categoryEntrance/classifyMap/' . $firClassifyId . '/edit'
                    ], ['text' => '前台二级级类目配置']);
                break;
            case mShopCategoryClassify::DEEP_THIRD_CLAORCATE:
                $basicForm->action('/admin/categoryEntrance/classifyMap/' . $firClassifyId . '/edit/' . $secClassifyId . '/edit/' . $classifyId . '/save');
                $content->header('前台' . mShopCategoryClassify::DEEP_CLASSIFY_DISPALY[$deep] . '级类目配置' . ($classifyId ? "-" . $childClassifyInfo['classify_name'] : ""))
                    ->breadcrumb([
                        'text' => '前台类目列表',
                        'url' => '/categoryEntrance/classifyMap'
                    ], [
                        'text' => '前台一级类目列表',
                        'url' => '/categoryEntrance/classifyMap/' . $firClassifyId . '/edit'
                    ], [
                        'text' => '前台二级类目列表',
                        'url' => '/categoryEntrance/classifyMap/' . $firClassifyId . '/edit/' . $secClassifyId . '/edit'
                    ], ['text' => '前台三级级类目配置']);
                break;
        }
        $tab->add('基础信息', $basicForm);
        if ($classifyId && $deep < mShopCategoryClassify::DEEP_THIRD_CLAORCATE) {
            $secGird = $this->childClassifyGrid($classifyId, $deep + 1, $childClassifyInfo['parent_id']);
            $tab->add('前台子类目', $secGird);
        }
        switch ($deep) {
            case mShopCategoryClassify::DEEP_SECOND_CLASSIFY:
                $basicForm->action('/admin/categoryEntrance/classifyMap/' . $firClassifyId . '/edit/' . $classifyId . '/save');
                break;
            case mShopCategoryClassify::DEEP_THIRD_CLAORCATE:
                $basicForm->action('/admin/categoryEntrance/classifyMap/' . $firClassifyId . '/edit/' . $secClassifyId . '/edit/' . $classifyId . '/save');
                break;
        }
        $content->row($tab);
        return $content;
    }

    /**
     * 保存一级类目修改
     * @param Request $request
     * @param int $firClassifyId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveClassify(Request $request, $firClassifyId = 0)
    {
        $data = [];
        $data['classify_name'] = $request->input('classify_name');
        $data['admin_id'] = Admin::user()->id;
        $data['deep'] = mShopCategoryClassify::DEEP_FIRST_CLASSIFY;
        try {
            if ($firClassifyId) {
                sShopClassify::admEditClassify($data, $firClassifyId);
            } else {
                $firClassifyId = sShopClassify::admAddClassifies($data);
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        return redirect('/admin/categoryEntrance/classifyMap/' . $firClassifyId . '/edit')->with(compact('success'));
    }

    /**
     * 保存二/三级类目修改
     * @param Request $request
     * @param $firClassifyId
     * @param int $secClassifyId
     * @param int $thirdClassifyId
     * @return \Illuminate\Http\RedirectResponse
     */
    public function saveChildClassify(Request $request, $firClassifyId, $secClassifyId = 0, $thirdClassifyId = 0)
    {
        $classifyId = $request->input('id');
        $data = [
            'classify_name' => $request->input('classify_name'),
            'icon' => $request->input('icon'),
            'parent_id' => $request->input('parent_id'),
            'deep' => $request->input('deep'),
            'admin_id' => Admin::user()->id
        ];


        $categoryStatusMap = [
            'decoration_status' => array_filter($request->input('decoration_status')),
            'house_status' => array_filter($request->input('house_status')),
        ];

        if(!$categoryStatusMap['decoration_status']) {
            throw new InputErrorException('推荐状态至少选择一个', InputErrorException::DEFAULT_CODE, 'decoration_status');
        }

        if(!$categoryStatusMap['house_status']) {
            throw new InputErrorException('房屋状态至少选择一个', InputErrorException::DEFAULT_CODE,'house_status');
        }

        try {
            if ($classifyId) {
                sShopClassify::admEditClassify($data, $classifyId, $request->input('cate_ids'), $categoryStatusMap);
            } else {
                $classifyId = sShopClassify::admAddClassifies($data, $request->input('cate_ids'), $categoryStatusMap);
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag([
            'title' => '保存成功'
        ]);
        switch ($request->input('deep')) {
            case mShopCategoryClassify::DEEP_SECOND_CLASSIFY:
                return redirect('/admin/categoryEntrance/classifyMap/' . $firClassifyId . '/edit/' . $classifyId . '/edit')->with(compact('success'));
                break;
            case mShopCategoryClassify::DEEP_THIRD_CLAORCATE:
                return redirect('/admin/categoryEntrance/classifyMap/' . $firClassifyId . '/edit/' . $secClassifyId . '/edit/' . $classifyId . '/edit')->with(compact('success'));
                break;
        }
    }

    /**
     * 前台类目排序
     * @param Request $request
     */
    public function sort(Request $request)
    {
        $sortInfo = $request->input('sort');
        sShopClassify::admSortCalssifies($sortInfo);
    }

    /**
     * 前台子类目列表
     * @param $childClassifyId
     * @param $deep
     * @return string
     */
    private function childClassifyGrid($childClassifyId, $deep, $firstClassifyId = 0)
    {

        $childClassfies = sShopClassify::admClassifiesOrCates($childClassifyId);
        $gridModel = new pGridDataModel($childClassfies['list']);
        return Admin::grid($gridModel, function (Grid $grid) use ($deep, $firstClassifyId) {
            $grid->disableExport();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disablePagination();
            $grid->column('id')->sort();
            $grid->column('classify_name', '前台' . mShopCategoryClassify::DEEP_CLASSIFY_DISPALY[$deep] . '级分类');
            $grid->column('icon_url', '图片')->image();
            if ($deep < mShopCategoryClassify::DEEP_THIRD_CLAORCATE) {
                $grid->column('classifies', '前台' . mShopCategoryClassify::DEEP_CLASSIFY_DISPALY[$deep + 1] . '级分类')->display(function () use ($deep, $firstClassifyId) {
                    $format = [];
                    if ($this->classifies) {
                        foreach ($this->classifies as $classify) {
                            $format[] = "<a href='/admin/categoryEntrance/classifyMap/{$firstClassifyId}/edit/{$classify['parent_id']}/edit/{$classify['id']}/edit'>{$classify['classify_name']}</a>";
                        }
                    }
                    return $format;
                })->label('default');
            }
            $grid->column('status', '隐藏')->switchToggle([
                'on' => [
                    'value' => mShopCategoryClassify::STATUS_NORMAL,
                    'text' => '展示'
                ],
                'off' => [
                    'value' => mShopCategoryClassify::STATUS_HIDE,
                    'text' => '隐藏'
                ]
            ]);
            $grid->column('cate_list', '关联后台类目')->display(function () {
                $format = [];
                if ($this->cate_list) {
                    foreach ($this->cate_list as $cate) {
                        //var_dump($cate);
                        $format[] = "<a href='/admin/category/edit/{$cate['id']}'>{$cate['deep']}级-{$cate['cate_name']}</a>";
                    }
                }
                return $format;
            })->badge("gray");;

        })->render();

    }

    /**
     * 删除前台类目
     * @param $firClassifyId
     * @param int $secClassifyId
     * @param int $thirdClassifyId
     * @return \Illuminate\Http\JsonResponse
     */
    public function delClassify($firClassifyId, $secClassifyId = 0, $thirdClassifyId = 0)
    {
        $classifyId = $thirdClassifyId ?: ($secClassifyId ?: $firClassifyId);
        sShopClassify::admdelClassify($classifyId);
        return response()->json([
            'status' => true,
            'message' => "删除成功",
        ]);
    }

    /**修改前台类目
     * @param Request $request
     * @param $firClassifyId
     * @param int $secClassifyId
     * @param int $thirdClassifyId
     * @return \Illuminate\Http\JsonResponse
     */
    public function editClassify(Request $request, $firClassifyId, $secClassifyId = 0, $thirdClassifyId = 0)
    {
        $classifyId = $thirdClassifyId ?: ($secClassifyId ?: $firClassifyId);
        $data = $request->all();
        sShopClassify::admputClassify($data, $classifyId);
        return response()->json([
            'status' => true,
            'message' => "修改成功",
        ]);
    }

}
